import axios from "axios";
import { getToken } from "@/utils/auth";
import { ElNotification } from "element-plus";
import router from "@/router";

const http = axios.create({
  baseURL: "http://localhost:9000/furniture/app",
  timeout: 5000,
});
http.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (getToken()) {
      config.headers["token"] = getToken();
      config.headers = {
        "Content-Type": "application/json",
        token: getToken(),
      };
    }
    return config;
  },
  (error) => {
    console.error(error);
    return Promise.reject(error);
  }
);

http.interceptors.response.use(
  (response) => {
    // 这才是真正的后台返回的响应报文
    let res = response.data;
    console.log(res);
    if (res.code === 401) {
      ElNotification({
        message: res.msg || "请登录后再操作！",
        title: "登录",
        type: "warning",
        duration: 5 * 1000,
      });
      // 跳转登录
      router.push("/login");
      return Promise.reject(new Error(res.msg || "请登录后再操作！"));
    } else if (res.code === 500) {
      ElNotification({
        message: res.msg || "系统内部异常，请联系管理员！",
        title: "系统异常",
        type: "error",
        duration: 5 * 1000,
      });
      return Promise.reject(
        new Error(res.msg || "系统内部异常，请联系管理员！")
      );
    } else {
      return res;
    }
  },
  (error) => {
    ElNotification({
      message: error.message,
      title: "系统异常",
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(new Error(error));
  }
);

export default http;
